package com.imooc.springcloud;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @describte:TODO
 * @program:spring-cloud-demo
 * @author:zhengdp
 * @create:2021-10-06 19:54:05
 **/
@Slf4j
@Service
public class JwtService {

    // 生产环境不能这么用
    private static final String KEY = "secretyKey";
    // 发行方，生产环境也不能这么用
    private static final String ISSUER = "zheng";

    private static final Long TOKEN_EXP_TIME = 60*1000L;

    private static final String USER_NAME = "username";

    /**
     * 生成token
     * @param acct
     * @return
     */
    public String token(Account acct){
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256("secretyKey");
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now) // key生成的时间
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXP_TIME))
                .withClaim(USER_NAME,acct.getUsername())
                //.withClaim("ROLE","权限")
                .sign(algorithm);
        log.info("jwt generated user={}",acct.getUsername());
        return token;
    }

    /**
     * 验证token
     * @param token
     * @param username
     * @return
     */
    public boolean verify(String token,String username){
        log.info("verifying jwt - username={}",username);
        try{
            // 加解密使用同一套算法
            Algorithm algorithm = Algorithm.HMAC256("secretyKey");
            JWTVerifier jwtVerifier = JWT.require(algorithm)
                                          .withIssuer(ISSUER)
                                          .withClaim(USER_NAME,username)
                                            .build();
            jwtVerifier.verify(token);
            return true;
        }catch (Exception e){
            log.error("auth failed",e);
            return false;
        }

    }
}
